package com.lplb.api.admin.service.impl.platform;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lplb.api.admin.mapper.AdminAuthMapper;
import com.lplb.api.admin.mapper.AdminUserMapper;
import com.lplb.api.admin.model.dto.AdminUserDTO;
import com.lplb.api.admin.model.entity.AdminAuth;
import com.lplb.api.admin.model.entity.AdminUser;
import com.lplb.api.admin.service.platform.LoginService;
import com.lplb.common.core.constant.base.BaseConstant;
import com.lplb.common.core.result.R;
import com.lplb.common.core.result.RType;
import com.lplb.common.core.service.BaseIServiceImpl;
import com.lplb.common.core.utils.auth.JwtUtil;
import com.lplb.common.core.utils.auth.MD5Util;
import com.lplb.common.coreconfig.config.ErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录/注册
 * @author wangsong
 * @mail 1720696548@qq.com
 * @date 2020/7/18 0018 11:30
 * @version 1.0.0
 */
@RestController
public class LoginServiceImpl extends BaseIServiceImpl<AdminUserMapper, AdminUser> implements LoginService {

    @Autowired
    private AdminAuthMapper adminAuthMapper;


    @Override
    public R<Void> login(String username, String password) {
        AdminUser adminUser = this.getOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getUsername, username));
        if (adminUser == null) {
            throw new ErrorException(RType.ADMIN_USERNAME_NOT_REGISTERED);
        }
        // 密码
        if (!adminUser.getPassword().equals(MD5Util.encode(password))) {
            throw new ErrorException(RType.ADMIN_ERROR_PASSWORD);
        }
        //是否禁用
        if (!adminUser.getState().equals(0)) {
            throw new ErrorException(RType.ADMIN_USERNAME_DISABLE);
        }
        // 登录成功
        // 查询用户当前所有权限资源取出所有权限url 放入用户信息中
        List<AdminAuth> authList = adminAuthMapper.findUidAuths(adminUser.getId());
        List<String> authUrls = authList.size() <= 0 ? null : authList.stream().map(AdminAuth::getUrl).collect(Collectors.toList());
        // 生成jwt
        String token = JwtUtil.generateToken(JSON.toJSONString(adminUser), authUrls);
        response.setHeader(BaseConstant.Sys.TOKEN, token);

        // 修改最后登录时间
        this.update(null, new LambdaUpdateWrapper<AdminUser>()
                .set(AdminUser::getEntTime, LocalDateTime.now())
                .eq(AdminUser::getId, adminUser.getId())
        );
        return R.success();
    }

    @Override
    public void register(@RequestBody @Validated AdminUserDTO dto) {

    }

    @Override
    public void outLogin() {

    }
}
